package com.qf.controller;

import com.github.pagehelper.PageInfo;
import com.qf.entity.Classsify;
import com.qf.entity.Dept;
import com.qf.entity.Role;
import com.qf.entity.User;
import com.qf.service.DeptService;
import com.qf.service.UserService;
import com.qf.utils.UserExcleUtil;
import com.qf.utils.NumberUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

/**
 * 2019/12/10
 * 郭程鹏
 * springboot_oa_five
 * 面向代码面向君,不负时光不负卿
 */
@Controller
public class PeopleController {

    @Autowired
    private UserService userService;

    @Autowired
    private DeptService deptService;


    //模糊分页查询
    @RequestMapping("/resource/system/user/list")
    public String userList(Model model, @RequestParam(defaultValue = "")String username, @RequestParam(defaultValue = "") String realName, @RequestParam(defaultValue = "1") Integer page, HttpSession session){

        HashMap<String, String> map = new HashMap<>();
        User loginUser = (User) session.getAttribute("user");
        model.addAttribute("loginUser",loginUser);

        map.put("username",username);
        map.put("realName",realName);
        PageInfo<User> allUsers = userService.findAllUsers(map, page);
        model.addAttribute("username",username);
        model.addAttribute("realName",realName);
        model.addAttribute("pageInfo",allUsers);



        return "resource/system/user/list";
    }

    //禁用
    @RequestMapping("/resource/system/user/status")
    public String setUserStatus(Model model,HttpServletResponse response, @RequestParam("userId") Integer userId, @RequestParam(defaultValue = "")String username, @RequestParam(defaultValue = "") String realName, @RequestParam(defaultValue = "1") Integer page,HttpSession session){

        response.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=utf-8");
        HashMap<String, String> map = new HashMap<>();

        map.put("username",username);
        map.put("realName",realName);

        try {
            int i = userService.setUserStausService(userId);

            if (i>0){
                response.getWriter().print("<script>alert('成功禁用')</script>");
                PageInfo<User> allUsers = userService.findAllUsers(map, page);
                model.addAttribute("pageInfo",allUsers);
                model.addAttribute("username",username);
                model.addAttribute("realName",realName);
                User loginUser = (User) session.getAttribute("user");
                model.addAttribute("loginUser",loginUser);
                return "resource/system/user/list";
            }else {
                response.getWriter().print("<script>alert('禁用失败')</script>");
                PageInfo<User> allUsers = userService.findAllUsers(map, page);
                model.addAttribute("pageInfo",allUsers);
                model.addAttribute("username",username);
                model.addAttribute("realName",realName);
                User loginUser = (User) session.getAttribute("user");
                model.addAttribute("loginUser",loginUser);
                return "resource/system/user/list";

            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    //启用
    @RequestMapping("/resource/system/user/active")
    public String setUserStatusActive(HttpSession session,Model model,HttpServletResponse response, @RequestParam("userId") Integer userId, @RequestParam(defaultValue = "")String username, @RequestParam(defaultValue = "") String realName, @RequestParam(defaultValue = "1") Integer page){

        response.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=utf-8");
        HashMap<String, String> map = new HashMap<>();

        map.put("username",username);
        map.put("realName",realName);

        try {
            int i = userService.setUserStausActive(userId);

            if (i>0){
                response.getWriter().print("<script>alert('已启用')</script>");
                PageInfo<User> allUsers = userService.findAllUsers(map, page);
                model.addAttribute("pageInfo",allUsers);
                model.addAttribute("username",username);
                model.addAttribute("realName",realName);
                User loginUser = (User) session.getAttribute("user");
                model.addAttribute("loginUser",loginUser);
                return "resource/system/user/list";
            }else {
                response.getWriter().print("<script>alert('系统繁忙！启用失败，请您稍后重试。')</script>");
                PageInfo<User> allUsers = userService.findAllUsers(map, page);
                model.addAttribute("pageInfo",allUsers);
                model.addAttribute("username",username);
                model.addAttribute("realName",realName);
                User loginUser = (User) session.getAttribute("user");
                model.addAttribute("loginUser",loginUser);
                return "resource/system/user/list";

            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }
    //跳转添加用户页面
    @RequestMapping("/resource/system/user/addftl")
    public String redirectToAdd(Model model){

        //部门
        List<Dept> allDept = deptService.findAllDept();
        //职位
        List<Classsify> classsify = deptService.findClasssify();
        //角色
        List<Role> roles = deptService.findRoles();
        model.addAttribute("allDept",allDept);
        model.addAttribute("classsify",classsify);
        model.addAttribute("allRole",roles);
        return "resource/system/user/add";
    }

    //添加用户
    @RequestMapping("/resource/system/user/add")
    public void addUser(User user,HttpServletResponse response){
        System.out.println(user);
        response.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=utf-8");

        try {
            int i = userService.addUser(user);
            if (i>0){
                response.getWriter().print("<script>alert('添加成功');location.href='/resource/system/user/list';</script>");
            }
        } catch (Exception e) {
            try {
                response.getWriter().print("<script>alert('添加失败');location.href='/resource/system/user/addftl';</script>");
            } catch (IOException ex) {
                ex.printStackTrace();
            }
            e.printStackTrace();
        }
    }



    //修改用户
    @RequestMapping("/resource/system/user/preEdit")
    public String  preUpdateUser(Integer userId,Model model){
        //部门
        List<Dept> allDept = deptService.findAllDept();
        //职位
        List<Classsify> classsify = deptService.findClasssify();
        //角色
        List<Role> roles = deptService.findRoles();
        User user = userService.preUpdate(userId);
        model.addAttribute("allDept",allDept);
        model.addAttribute("classsify",classsify);
        model.addAttribute("allRole",roles);
        model.addAttribute("user",user);
        return "resource/system/user/edit";
    }

    //修改信息
    @RequestMapping("/resource/system/user/update")
    public void updateUser(User user,HttpServletResponse response){
        System.out.println(user);

        response.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=utf-8");
        try {
            int i = userService.updateUser(user);
            if (i>0){
                response.getWriter().print("<script>alert('修改成功');window.history.back();</script>");
            }else {
                response.getWriter().print("<script>alert('修改失败');window.history.back();</script>");
            }
        } catch (IOException e) {
            try {
                response.getWriter().print("<script>alert('修改失败');window.history.back();</script>");
            } catch (IOException ex) {
                ex.printStackTrace();
            }
            e.printStackTrace();
        }


    }

    //单个删除
    @RequestMapping("/resource/system/user/deletOne")
    public String deleteOne(HttpSession session,Model model,HttpServletResponse response, @RequestParam("userId") Integer userId, @RequestParam(defaultValue = "")String username, @RequestParam(defaultValue = "") String realName, @RequestParam(defaultValue = "1") Integer page){
        response.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=utf-8");
        HashMap<String, String> map = new HashMap<>();
        System.out.println(userId);

        map.put("username",username);
        map.put("realName",realName);
        try {
            int i = userService.deleteUserEmpById(userId);
            if (i>0){
                response.getWriter().print("<script>alert('删除成功')</script>");
                PageInfo<User> allUsers = userService.findAllUsers(map, page);
                model.addAttribute("pageInfo",allUsers);
                model.addAttribute("username",username);
                model.addAttribute("realName",realName);
                User loginUser = (User) session.getAttribute("user");
                model.addAttribute("loginUser",loginUser);
                return "resource/system/user/list";
            }else {
                response.getWriter().print("<script>alert('删除成功')</script>");
                PageInfo<User> allUsers = userService.findAllUsers(map, page);
                model.addAttribute("pageInfo",allUsers);
                model.addAttribute("username",username);
                model.addAttribute("realName",realName);
                User loginUser = (User) session.getAttribute("user");
                model.addAttribute("loginUser",loginUser);
                return "resource/system/user/list";

            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }


    //批量删除和导出
    @RequestMapping("/resource/system/user/delAllAndExcle")
    public void delAllAndExcle(@RequestParam("roleId") List<Integer> roleId,@RequestParam("loginUserId") Integer loginUserId,@RequestParam("userId") List<Integer> userId, @RequestParam("method") String method, HttpServletResponse response){
        response.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=utf-8");
        for (Integer integer : userId) {
            System.out.println(integer);
        }

        if (method.equals("deleteAll")){
            ArrayList<Integer> roleIdS = new ArrayList<>();
            for (Integer id : roleId) {
                if (loginUserId>=id){
                   roleIdS.add(id);
                   break;
                }
            }

            if (roleIdS.size()>0){
                String userNameByRoleId = userService.findUserNameByRoleId(roleIdS);

                try {
                    response.getWriter().print("<script>alert('权限不足，你不能删除"+userNameByRoleId+"');window.history.back();</script>");
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }else {
                try {
                    userService.deleteUserEmpMany(userId);

                    response.getWriter().print("<script>alert('删除成功');location.href='/resource/system/user/list';</script>");

                } catch (Exception e) {
                    try {
                        response.getWriter().print("<script>alert('删除失败');location.href='/resource/system/user/list';</script>");
                    } catch (IOException ex) {
                        ex.printStackTrace();
                    }
                    e.printStackTrace();
                }
            }



        }else if (method.equals("doExcle")){
            ServletOutputStream outputStream=null;

            try {
                outputStream = response.getOutputStream();
                List<User> excle = userService.getExcle(userId);

                //生成随机名字
                String number = NumberUtil.getNumber(6);
                //设置导出格式
                response.setContentType("application/x-download");
                String excleName = "excle_"+number+ ".xls";
                response.addHeader("Content-Disposition", "attachment;filename=" + excleName);
                //设置表名
                UserExcleUtil.createFirstRow("用户信息");
                //设置类容
                UserExcleUtil.createSheetValue(excle);
                UserExcleUtil.export(outputStream);
                return;

            } catch (IOException e) {
                    try {
                    response.getWriter().print("<script>alert('失败');window.history.back();</script>");
                } catch (IOException ex) {
                    ex.printStackTrace();
                }
                e.printStackTrace();
            }catch (IllegalStateException e){
                try {
                    response.getWriter().print("<script>alert('导出成功');window.history.back();</script>");
                } catch (IOException ex) {
                    ex.printStackTrace();
                }
            }finally {
                try {
                    outputStream.flush();
                    outputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }


        }

    }


    //异步校验用户名
    @RequestMapping("/resource/system/user/ajaxUsername")
    @ResponseBody
    public Integer ajaxUserId(@RequestParam("username") String username){
        Integer userId = userService.ajaxUserId(username);

        return userId;
    }


    //查看用户信息
    @RequestMapping("/resource/system/user/look")
    public String lookUser(Integer userId,Model model){

        User user = userService.lookUser(userId);
        model.addAttribute("user",user);
        return "resource/system/user/look" ;

    }

}
